package com.atguigu.OssServoce.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.OssServoce.service.OssService;
import com.atguigu.OssServoce.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId=ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret= ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName= ConstantPropertiesUtil.BUCKET_NAME;

        InputStream inputStream = null;
        try {
            OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            originalFilename = uuid + originalFilename;

            String datePath = new DateTime().toString("yyyy/MM/dd");

//            拼接
            originalFilename=datePath+"/"+originalFilename;

            ossClient.putObject(bucketName,originalFilename,inputStream);
            ossClient.shutdown();
            String url="https://"+bucketName+"."+endpoint+"/"+originalFilename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
